import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex); //把vuex注入到所有到的子组件

import * as api from "../api"

import allRoutes from '../router/allRoutes'
import dynamicRoutes from '../router/dynamicRoutes'
import recursionRoutes from "../utils/recursionRoutes";//递归计算用户路由的方法

import router from "../router";

let userInfo = localStorage.getItem("qf-userInfo") || "{}";

export default new Vuex.Store({
  // strict:true,
  //vuex五大核心
  state: {
    userInfo: JSON.parse(userInfo),//用户信息
    sideMenu: [],//侧边栏信息
    breadCrumb: [],//面包屑
    dialogVisible: false,//控制dialog显得隐藏的值
    dialogTitle: "增加学员信息",//控制dialog标题
    stuData: [],
    loading: true,//表格加载动画控制
    currentRow: {}, //dialog回显的表格数据
    stuTotal: 0,//总条目
    stuPageSize: 10 //每页显示的数量
  }, //状态

  mutations: {
    SET_USER_INFO(state, payload) {//设置用户线
      state.userInfo = payload;
    },

    SET_MENULIST(state, payload) {//设置菜单
      state.sideMenu = [...payload];
      //设置dynamicRoutes=>讲用户路由添加到当前数组中的path="/"的对象的children属性中
      //添加完成之后,还需要将整个dynamicRoutes通过addRoutes的方式添加到系统路由routes中
      let target = dynamicRoutes.find(item => item.path === "/");
      target.children = [...payload];
      //将dynamicRoutes动态添加到路由中
      // console.log(dynamicRoutes)
      router.addRoutes(dynamicRoutes)

    },

    SET_BREADCRUMB(state, payload) { //面包屑
      state.breadCrumb = payload
    },

    SHOW_DIALOG(state) {//显示dialog
      state.dialogVisible = true
    },

    HIDE_DIALOG(state) {//隐藏dialog
      state.dialogVisible = false
    },

    CHANGE_DIALOG_TITLE(state, payload) { //修改dialog标题
      state.dialogTitle = payload
    },

    SET_STU_DATA(state, payload) {//设置学员项目管理表格中的数据
      state.stuData = payload.data//设置学员列表
      state.loading = false //关闭加载动画
      state.stuTotal = payload.total //设置学员分页总数
    },

    //表格显示loading动画
    SHOW_LOADING(state) {
      state.loading = true
    },

    //表格隐藏loading动画
    HIDE_LOADING(state) {
      state.loading = false
    },

    //修改dialog回显数据
    SET_CURRENT_ROW(state, payload) {
      state.currentRow = { ...payload }
    }
  }, //修改状态的方法

  actions: {
    //发起异步请求,然后获取用户菜单
    GET_MENULIST({ commit }) { //获取用户菜单
      // console.log(allRoutes,65565565);
      //发请求获取用户菜单
      return api.getMenuListApi()
        .then(res => {
          let menuList = res.data.menuList;
          // console.log(menuList);
          //递归,匹配出用户路由
          let userMenu = recursionRoutes(allRoutes, menuList);
          // console.log('userMenu',userMenu);
          commit("SET_MENULIST", userMenu)
        })
    },
    GET_STULIST({ commit }, payload = {}) {//获取学员列表
      commit("SHOW_LOADING") //打开加载动画
      let { page = 1, count = 10, classes = "" } = payload
      api.getStuListApi(page, count, classes)
        .then(res => {
          commit("SET_STU_DATA", res.data)
        })
    }
  },

  getters: {}, //相当于是vuex中的计算属性

  modules: {}, //模块化
});
